package com.gitee.zhangchenyan.takin.service.server;

import cn.hutool.core.convert.Convert;
import com.gitee.zhangchenyan.takin.common.utils.HostUtils;
import com.gitee.zhangchenyan.takin.service.common.AlibabaNacos;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

@Slf4j
@Component
public class TakinServiceServerBean implements ApplicationContextAware {

    private final Environment environment;
    public TakinServiceServerBean(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        nacosRegisterServer(applicationContext);
    }

    @SneakyThrows
    private void nacosRegisterServer(ApplicationContext applicationContext) {
        AlibabaNacos bean = applicationContext.getBean(AlibabaNacos.class);
        String ip = "";
        if (environment.containsProperty("takin.rpcServerIp")) {
            ip = environment.getProperty("takin.rpcServerIp");
        } else {
            ip = HostUtils.getHostIp();
        }
        int port = 0;
        if (environment.containsProperty("takin.rpcServerPort")) {
            port = Convert.toInt(environment.getProperty("takin.rpcServerPort"));
        } else {
            port = Convert.toInt(environment.getProperty("server.port"));
        }
        String nacosServerName = environment.getProperty("takin.contractPackage");
        bean.registerServer(nacosServerName, ip, port);
    }
}
